/// @file
/// @author Chelsey Batchelor <vadedeyes@gmail.com>
/// @author Abraham Escamilla <abraham.escamilla@live.com>
/// @author Curtis Hollibaugh <curtis.hollibaugh@gmail.com>
/// @copyright Copyright 2014 Chelsey Batchelor <vadedeyes@gmail.com>
/// @copyright Copyright 2014 Abraham Escamilla <abraham.escamilla@live.com>
/// @copyright Copyright 2014 Curtis Hollibaugh <curtis.hollibaugh@gmail.com>
/// Contains definitions for the GUI class.

#include "gtk.hpp"
#include "gui.hpp"

using std::lock_guard;
using std::mutex;
using std::thread;

GUI::GUI()
:	isRunning{false}, isRunningMutex{}, mainLoopThread{} {
	Gtk::Init();
}

GUI::~GUI() {
	Stop();
}

bool GUI::IsRunning() {
	lock_guard<mutex> lock{isRunningMutex};
	return isRunning;
}

void GUI::Start() {
	isRunningMutex.lock();
	if(!isRunning) {
		isRunning = true;
		isRunningMutex.unlock();
		
		auto mainLoop = [&](){
			while(true) {
				isRunningMutex.lock();
				if(!isRunning) {
					isRunningMutex.unlock();
					break;
				}
				else {
					isRunningMutex.unlock();
				}
				
				Gtk::MainIterationDo();
			}
		};
		
		mainLoopThread = thread{mainLoop};
	}
	else {
		isRunningMutex.unlock();
	}
}

void GUI::Stop() {
	isRunningMutex.lock();
	if(isRunning) {
		isRunning = false;
		isRunningMutex.unlock();
		mainLoopThread.join();
	}
	else {
		isRunningMutex.unlock();
	}
}
